var fs = require('fs');
var path = require('path');
var sha1 = require('sha1');
var express = require('express');
var router = express.Router();

var UserModel = require('../models/users');
var StudentModel = require('../models/students');
var checkNotLogin = require('../middlewares/check').checkNotLogin;

// GET /signup 注册页
router.get('/', checkNotLogin, function(req, res, next) {
    var user_id = req.query.user_id;
    // var name = req.query.name;

    if (user_id) { // 自动注册登录
        UserModel.getUserById(user_id)
            .then(function (user) {
                if (!user) {
                    return res.render('signup', {
                        user_id : user_id,
                        name : ""
                    });
                }
                res.redirect(`/posts?author=${user._id}`);
            })
            .catch(next);
    } else {
        res.render('signup', {
            user_id : "",
            name : ""
        });
    }
});

// POST /signup 用户注册
router.post('/', checkNotLogin, function(req, res, next) {
    var user_id = req.fields.user_id;
    var name = req.fields.name;
    var gender = req.fields.gender;
    var identity = req.fields.identity;
    // var student_name = req.fields.student_name;
    var student_id = req.fields.student_id;
    var teacher_id = req.fields.teacher_id;
    var bio = ""; // req.fields.bio;
    var avatar = req.files.avatar.path.split(path.sep).pop();
    var password = ""; // req.fields.password;
    var repassword = ""; // req.fields.repassword;

    // 校验参数
    try {
        if (!(name.length >= 1 && name.length <= 20)) {
            throw new Error('名字请限制在 1-20 个字符');
        }
        if (!user_id) {
            user_id = name;
        }

        if ('教师' == identity) {
            // TODO 校验教师证号的合法性
            if (!(teacher_id.length >= 1 && teacher_id.length <= 20)) {
                throw new Error('教师证号请限制在 1-20 个字符');
            }
        }

        // if (!(bio.length >= 1 && bio.length <= 30)) {
        //     throw new Error('个人简介请限制在 1-30 个字符');
        // }
        if (!req.files.avatar.name) {
            fs.unlink(req.files.avatar.path);
            avatar = "";
        }
        // if (password.length < 6) {
        //     throw new Error('密码至少 6 个字符');
        // }
        // if (password !== repassword) {
        //     throw new Error('两次输入密码不一致');
        // }
    } catch (e) {
        // 注册失败，异步删除上传的头像
        fs.unlink(req.files.avatar.path);
        req.flash('error', e.message);
        return res.redirect('/signup', {
            user_id : user_id,
            name : name
        });
    }

    // 明文密码加密
    password = sha1(password);

    // 待写入数据库的用户信息
    var user = {
        user_id: user_id,
        name: name,
        password: password,
        gender: gender,
        identity: identity,
        // student_name: student_name,
        student_id: student_id,
        teacher_id: teacher_id,
        bio: bio,
        avatar: avatar
    };

    if ('家长' == identity) {
        // TODO
        StudentModel.getStudentById(student_id)
            .then(function (student) {
                if (!student) {
                    throw new Error('该学生不存在');
                } else {
                    createUser(req, res, next, user);
                }
            })
            .catch(function (e) {
                // 注册失败，异步删除上传的头像
                if (req.files.avatar.path) {
                    fs.unlink(req.files.avatar.path);
                }
                req.flash('error', e.message);
                return res.redirect('signup', {
                    user_id : user_id,
                    name : name
                });
            });
    } else {
        createUser(req, res, next, user);
    }

});

function createUser(req, res, next, user) {
    // 用户信息写入数据库
    UserModel.create(user)
        .then(function (result) {
            // 此 user 是插入 mongodb 后的值，包含 _id
            user = result.ops[0];
            // 将用户信息存入 session
            delete user.password;
            req.session.user = user;
            // 写入 flash
            req.flash('success', '注册成功');

            // 跳转到首页
            res.redirect(`/posts?author=${user._id}`);
        })
        .catch(function (e) {
            // 注册失败，异步删除上传的头像
            if (req.files.avatar.path) {
                fs.unlink(req.files.avatar.path);
            }
            // 用户名被占用则跳回注册页，而不是错误页
            console.log("注册失败: " + e.message);
            if (e.message.match('E11000 duplicate key')) {
                req.flash('error', '用户名已被占用');
                return res.redirect('signup', {
                    user_id : user.user_id,
                    name : user.name
                });
            }
            next(e);
        });
}

module.exports = router;
